package com.shengdacar.sharelibrary.wx;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;

import androidx.core.content.FileProvider;

import com.shengdacar.sharelibrary.callback.AsyncCallBack;
import com.shengdacar.sharelibrary.callback.NoInstalled;
import com.shengdacar.sharelibrary.utils.BitmapSaveAsyncTask;
import com.shengdacar.sharelibrary.utils.FileIconProvideDefault;
import com.shengdacar.sharelibrary.utils.FileUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXFileObject;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.io.File;

/**
 * 作者：huyi
 * 日期：2020/12/17 10:12
 * 描述：
 */
public class WxShareUtil {


    private static final int THUMB_SIZE = 150;

    private int mTargetScene = FRIENDS;

    public static final int FRIENDS = SendMessageToWX.Req.WXSceneSession; //分享给朋友
    public static final int FRIENDS_CIRCLE = SendMessageToWX.Req.WXSceneTimeline;//分享到朋友圈
    public static final int FAVORITE = SendMessageToWX.Req.WXSceneFavorite;//分享到收藏
    public static final int IMG = 0;
    public static final int FILE = 1;

    private WxShareUtil() {

    }

    public static WxShareUtil newInstance() {
        return new WxShareUtil();
    }

    private NoInstalled noInstalled;

    /**
     * 注册微信未安装监听
     */
    public WxShareUtil setNoInstalled(NoInstalled noInstalled) {
        this.noInstalled = noInstalled;
        return this;
    }

    private NoInstalled getNoInstalled() {
        if (null == noInstalled) {
            noInstalled = (transaction) -> {
            };
        }
        return noInstalled;
    }

    /**
     * @param SHARE_TYPE 设置分享类型
     */
    public WxShareUtil setmTargetScene(int SHARE_TYPE) {
        this.mTargetScene = SHARE_TYPE;
        return this;
    }


    /**
     * 微信纯文本分享
     *
     * @param msg
     */
    public void wxTxtShare(String msg) {
        if (wxNoInstalled()) {
            return;
        }
        if (TextUtils.isEmpty(msg)) {
            getNoInstalled().noInstalled("分享的文本是空");
            return;
        }
        WXTextObject textObj = new WXTextObject();
        textObj.text = msg;
        WXMediaMessage msg1 = new WXMediaMessage();
        msg1.mediaObject = textObj;
        msg1.description = msg;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("text");
        req.message = msg1;
        req.scene = mTargetScene;
        WxApiGlobal.getInstance().getWXAPI().sendReq(req);
    }

    /**
     * 网页分享
     *
     * @param mContext    上下文
     * @param webUrl      分享的网址
     * @param title       分享的标题
     * @param description 分享的描述
     * @param picture     分享的资源图片，drawable和mipmap文件夹中取R.drawable.icon
     */
    public void wxHttpShare(Context mContext, String webUrl, String title, String description, int picture) {
        if (wxNoInstalled()) {
            return;
        }
        if (TextUtils.isEmpty(webUrl)) {
            getNoInstalled().noInstalled("分享的链接是空");
            return;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = webUrl;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = description;
        //设置缩略图
        Bitmap bmp = BitmapFactory.decodeResource(mContext.getResources(), picture);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
        bmp.recycle();
        msg.thumbData = Tools.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = mTargetScene;
        WxApiGlobal.getInstance().getWXAPI().sendReq(req);
    }


    /**
     * 微信分享bitmap,使用路劲分享，字节分享大小有限制
     *
     * @param context 上下文
     * @param bitmap  图片bitmap
     * @param path    图片bitmap保存的路劲，针对android11分享图片需要按照fileProvider方式
     */
    public void wxShareBitmap(Context context, Bitmap bitmap, String path) {
        if (wxNoInstalled()) {
            return;
        }
        if (bitmap == null) {
            getNoInstalled().noInstalled("分享的图片是空");
            return;
        }
        if (TextUtils.isEmpty(path)) {
            path = context.getExternalFilesDir(null).getAbsolutePath();
        }
        String fileName = "img_" + System.currentTimeMillis() + ".jpg";
        BitmapSaveAsyncTask bitmapSaveAsyncTask = new BitmapSaveAsyncTask(path, fileName, new AsyncCallBack() {
            @Override
            public void fileBack(File file) {
                wxFileShare(context, file, IMG, "");
            }
        });
        bitmapSaveAsyncTask.execute(bitmap);
    }

    /**
     * 微信分享文件，使用路劲分享，字节分享有大小限制
     *
     * @param context 上下文
     * @param file    文件
     * @param type    类型
     */
    public void wxFileShare(Context context, File file, int type, String shareFileName) {
        if (wxNoInstalled()) {
            return;
        }
        if (file == null || !file.exists()) {
            getNoInstalled().noInstalled("分享的文件不存在");
            return;
        }
        //设置分享路径
        String sharePath = "";
        if (checkVersionValid() && checkAndroidNotBelowN()) {
            // 使用contentPath作为文件路径进行分享
            sharePath = getFileUri(context, file);
        } else {
            // 使用原有方式传递文件路径进行分享
            sharePath = file.getAbsolutePath();
        }
        WXMediaMessage msg = new WXMediaMessage();
        if (type == IMG) {//分享图片
            WXImageObject wxImageObject = new WXImageObject();
            wxImageObject.setImagePath(sharePath);
            msg.mediaObject = wxImageObject;
            //设置缩略图
            Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
            bmp.recycle();
            msg.thumbData = Tools.bmpToByteArray(thumbBmp, true);
        } else {
            WXFileObject wxFileObject = new WXFileObject();
            wxFileObject.setFilePath(sharePath);
            msg.mediaObject = wxFileObject;
            if (TextUtils.isEmpty(shareFileName)) {
                msg.title = file.getName();
            } else {
                msg.title = shareFileName + FileUtils.getFileSuffix(file);
            }
            Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), new FileIconProvideDefault().getFileDrawableResId(context, file));
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
            bmp.recycle();
            msg.thumbData = Tools.bmpToByteArray(thumbBmp, true);
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        if (type == IMG) {//分享图片
            req.transaction = buildTransaction("img");//  transaction字段用
        } else {
            req.transaction = buildTransaction(null);//  transaction字段用
        }
        req.message = msg;
        req.scene = mTargetScene;
        WxApiGlobal.getInstance().getWXAPI().sendReq(req);
    }


    public String getFileUri(Context context, File file) {
        if (file == null || !file.exists()) {
            return null;
        }
        Uri contentUri = FileProvider.getUriForFile(context,
                context.getPackageName() + ".wechatShare",  // 要与`AndroidManifest.xml`里配置的`authorities`一致，假设你的应用包名为com.example.app
                file);
        // 授权给微信访问路径
        context.grantUriPermission("com.tencent.mm",  // 这里填微信包名
                contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

        return contentUri.toString();   // contentUri.toString() 即是以"content://"开头的用于共享的路径
    }

    // 判断微信版本是否为7.0.13及以上
    public boolean checkVersionValid() {
        return WxApiGlobal.getInstance().getWXAPI().getWXAppSupportAPI() >= 0x27000D00;
    }

    // 判断Android版本是否7.0及以上
    public boolean checkAndroidNotBelowN() {
        return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    /**
     * 注册回调接口，并检查是否安装微信
     */
    private boolean wxNoInstalled() {
        //检查是否安装微信客户端
        if (!WxApiGlobal.getInstance().getWXAPI().isWXAppInstalled()) {
            getNoInstalled().noInstalled("请安装微信客户端");
            return true;
        }
        return false;
    }
}
